<?php

namespace ASW\Utility\HttpClient;

/**
 * Class ResponseRedirect
 *
 * @package lib\Util\HttpClient
 *
 * @property-read string $httpVersion
 * @property-read int $httpCode
 * @property-read string $httpStatus
 * @property-read array $headers
 * @property-read string $location
 * @property-read array $cookies
 */
class ResponseRedirect
{
    private array $_properties = [];

    public static function fromResponseHeaderPackage(string $headerPackage): self
    {
        $instance = new self();
        /*
            * HTTP/1.1 301 Moved Permanently
            * Server: nginx/1.14.1
            * Date: Thu, 21 May 2020 12:03:40 GMT
            * Content-Type: text/html
            * Content-Length: 185
            * Connection: keep-alive
            * Location: https://app-server.paoniula.com/
         * */

        $headerPackageLines = explode("\n", trim($headerPackage));
        $headerFirstLine    = array_shift($headerPackageLines);
        if (1 === preg_match("/^(HTTP\/\d\.\d) (\d{3})(.*)$/", $headerFirstLine, $matches)) {
            $instance->_properties['httpVersion'] = $matches[1];
            $instance->_properties['httpCode']    = intval($matches[2]);
            $instance->_properties['httpStatus']  = $matches[3];
        }

        foreach ($headerPackageLines as $headerLine) {
            if (strpos($headerLine, ':') === false) continue;

            [$headerKey, $headerVal] = explode(":", $headerLine);
            $headerKey = trim($headerKey);
            $headerKey = str_replace(' ', '-', ucwords(str_replace('-', ' ', $headerKey)));
            $headerVal = trim($headerVal);
            if ($headerKey == 'Set-Cookie') {
                $instance->_properties['cookies'][] = ResponseCookie::fromSetCookieHeaderLine($headerVal);
            } else {
                if ($headerKey === 'Location') $instance->_properties['location'] = $headerVal;
                $instance->_properties['headers'][$headerKey] = $headerVal;
            }
        }

        return $instance;
    }

    public function __get(string $propertyName)
    {
        if (!array_key_exists($propertyName, $this->_properties)) return null;

        return $this->_properties[$propertyName];
    }
}